package com.wzb.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzb.common.util.PageResult;
import com.wzb.entity.Classes;
import com.wzb.entity.Student;
import com.wzb.mapper.StudentMapper;
import com.wzb.service.IClassesService;
import com.wzb.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzb.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzb
 * @since 2025-01-08
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
    @Autowired
    private IClassesService classesService;

    // 1. 分页查询
    @Override
    public PageResult<Student> findByPage(Integer page, Integer pageSize) {
        // 使用分页插件的分页
        Page<Student> pageResult = this.page(new Page<>(page, pageSize));
        return buildPageResult(pageResult);
    }

    // 3. 条件带分页查询
    @Override
    public PageResult<Student> search(Integer page, Integer pageSize, StudentVO vo) {
        // 1. 封装查询条件
        QueryWrapper<Student> wrapper = buildQueryWrapper(vo);

        // 2. 分页查询
        Page<Student> pageResult = this.page(new Page<>(page, pageSize), wrapper);

        // 3. 处理学生所在班级名称，避免空指针
        pageResult.getRecords().forEach(st -> {
            Classes classes = classesService.getById(st.getCid());
            if (classes != null) {
                st.setCname(classes.getCname());
            }
        });

        return buildPageResult(pageResult);
    }

    // 添加学生
    @Override
    public boolean add(Student student) {
        return this.save(student);
    }

    // 统一封装分页查询的结果
    private PageResult<Student> buildPageResult(Page<Student> pageResult) {
        return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
    }

    // 封装条件构建逻辑
    private QueryWrapper<Student> buildQueryWrapper(StudentVO vo) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(vo.getSname())) {
            wrapper.like("sname", vo.getSname());
        }
        if (StrUtil.isNotBlank(vo.getAddr())) {
            wrapper.like("addr", vo.getAddr());
        }
        if (vo.getCid() != null && vo.getCid() != 0) {
            wrapper.eq("cid", vo.getCid());
        }
        return wrapper;
    }
}

